<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机泡泡</title>
    <style>
        #cs{
            border:1px solid red;
        }
    </style>
</head>
<body>

    <canvas id="cs" width="800" height="500"></canvas>
    <script>
        let cs = document.getElementById("cs");
        let ctx = cs.getContext("2d");
        // 封装产生随机数的方法
        function random(start,end){
            if(!end){
                return parseInt(Math.random() * start);
            }
            return parseInt(Math.random() * (end - start + 1) + start);

        }

        class Popup{
            constructor(){
                this.x = random(800);
                this.y = random(500);
                this.r = random(25,75);
                this.color = `rgb(${random(255)},${random(255)},${random(255)})`;
                this.direct = 1;
                this.scaleValue = 1;
                this.speed = random(10,100);
            }
            draw(){
                ctx.beginPath();
                ctx.save();
                ctx.translate(this.x,this.y);
                if(this.scaleValue >= 2 || this.scaleValue <= 0){
                    this.direct *= -1;
                }
                this.scaleValue += 1 / this.speed * this.direct;
                ctx.scale(this.scaleValue,this.scaleValue);
                ctx.globalAlpha = this.scaleValue;
                ctx.fillStyle = this.color;
                ctx.arc(0,0,this.r,0,2*Math.PI);
                ctx.fill();
                ctx.restore();
            }
        }
        let popAry = [];
        for(let i = 0;i < 20;i++){
            popAry.push(new Popup());
        }
        setInterval(function(){
            ctx.clearRect(0,0,800,500);
            for(let i = 0;i < 20;i++){
                popAry[i].draw();
            }
        },50);
    </script>
</body>
</html>